package com.tyk.bookstore.back.system.valid.validator;

import com.tyk.bookstore.back.common.core.valid.util.ValidUtil;
import com.tyk.bookstore.back.system.valid.annotation.RoleFieldValid;
import com.tyk.bookstore.back.system.valid.constant.RoleFieldValidConstant;
import com.tyk.bookstore.back.system.valid.type.RoleFieldValidType;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

public class RoleFieldConstraintValidator implements ConstraintValidator<RoleFieldValid, Object> {
    private RoleFieldValidType[] types;

    @Override
    public void initialize(RoleFieldValid roleFieldValid) {
        types = roleFieldValid.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }

        for (RoleFieldValidType type : types) {
            switch (type) {
                case CODE, CODE_LIKE -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String)value, RoleFieldValidConstant.CODE_MIN_LENGTH, RoleFieldValidConstant.CODE_MAX_LENGTH, RoleFieldValidConstant.CODE_PATTERN);
                    }
                }
                case NAME, NAME_LIKE -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, RoleFieldValidConstant.NAME_MIN_LENGTH, RoleFieldValidConstant.NAME_MAX_LENGTH, RoleFieldValidConstant.NAME_PATTERN);
                    }
                }
                case DESCRIPTION -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, RoleFieldValidConstant.DESCRIPTION_MIN_LENGTH, RoleFieldValidConstant.DESCRIPTION_MAX_LENGTH);
                    }
                }
            }
        }

        throw new IllegalArgumentException("非法取值" + Arrays.toString(types) + value);
    }
}
